import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ChunkMergeTest {

    // 分块文件合并测试
    public static void main(String[] args) throws IOException {
        // 分块文件目录
        File chunkFolder = new File("D:\\develop\\file_chunk\\");
        // 原始文件
        File originalFile = new File("D:\\video3.mp4");
        // 合并后的文件
        File mergedFile = new File("D:\\video3_01.mp4");

        if (mergedFile.exists()) {
            mergedFile.delete();
        }
        mergedFile.createNewFile();

        // 用于写文件
        RandomAccessFile raf_writer = new RandomAccessFile(mergedFile, "rw");
        // 指针指向文件顶端
        raf_writer.seek(0);
        // 缓冲区
        byte[] b = new byte[1024];
        // 分块文件列表
        File[] fileArray = chunkFolder.listFiles();
        // 转成集合，方便排序
        List<File> fileList = Arrays.asList(fileArray);
        // 从小到大排序
        Collections.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                return Integer.parseInt(o1.getName()) - Integer.parseInt(o2.getName());
            }
        });

        // 合并文件
        for (File chunkFile : fileList) {
            RandomAccessFile raf_read = new RandomAccessFile(chunkFile, "r");
            int len = -1;
            while ((len = raf_read.read(b)) != -1) {
                raf_writer.write(b, 0, len);
            }
            raf_read.close();
        }
        raf_writer.close();

        // 校验文件
        try (FileInputStream fileInputStream = new FileInputStream(originalFile);
             FileInputStream mergeInputStream = new FileInputStream(mergedFile);) {
            // 取出原始文件的MD5值
            String originalMd5 = DigestUtils.md5Hex(fileInputStream);
            String mergeMd5 = DigestUtils.md5Hex(mergeInputStream);
            if (!originalMd5.equals(mergeMd5)) {
                System.out.println("合并文件失败");
            } else {
                System.out.println("合并文件成功");
            }
        }

    }

}
